package com.jcfk.system.service;

import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.jcfk.common.business.enums.DeleteFlag;
import com.jcfk.common.business.service.BaseService;
import com.jcfk.common.cache.redis.service.RedisHashService;
import com.jcfk.common.core.utils.BeanUtils;
import com.jcfk.common.core.utils.IdUtils;
import com.jcfk.common.security.utils.SecurityUtils;
import com.jcfk.common.web.domain.RetResult;
import com.jcfk.system.dao.SysOrganizationDao;
import com.jcfk.system.domain.dto.SysOrganizationDTO;
import com.jcfk.system.domain.po.RefUserOrganizationMapping;
import com.jcfk.system.domain.po.SysOrganization;
import com.jcfk.system.domain.po.SysUser;
import com.jcfk.system.domain.query.SysOrganizationQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 组织机构 业务逻辑
 *
 * @author qinjiaxing
 */
@Service
public class SysOrganizationService extends BaseService<SysOrganizationDao, SysOrganization> {

    /**
     * Redis 缓存键名
     */
    private static final String redisKeyName = "ServiceCache:SysOrganization";

    @Autowired
    private RedisHashService redisHashService;

    @Autowired
    private RefUserOrganizationMappingService refUserOrganizationMappingService;

    @Autowired
    private SysUserService sysUserService;


    /**
     * 根据条件获取多级分类列表
     *
     * @param query 查询条件
     * @return List<CustomMultilevelKindDTO>
     */
    public List<SysOrganizationDTO> getList(SysOrganizationQuery query) {
        // 查询条件
        QueryWrapper<SysOrganization> qw = new QueryWrapper<>();
        if (!StrUtil.isEmpty(query.getOrganizationCode())) {
            qw.lambda().eq(SysOrganization::getOrganizationCode, query.getOrganizationCode());
        }

        if (!StrUtil.isEmpty(query.getOrganizationName())) {
            qw.lambda().like(SysOrganization::getOrganizationName, query.getOrganizationName());
        }

        if (query.getOrganizationType() != null) {
            qw.lambda().eq(SysOrganization::getOrganizationType, query.getOrganizationType());
        }

        if (query.getEnabled() != null) {
            qw.lambda().eq(SysOrganization::getEnabled, query.getEnabled());
        }

        qw.lambda().eq(SysOrganization::getDeleted, DeleteFlag.NOTDELETED.getValue());
        qw.orderByAsc("sort");
        // 查询数据
        List<SysOrganization> sysOrganizationList = super.list(qw);
        List<SysOrganizationDTO> sysOrganizationArray = new ArrayList<>();
        for (SysOrganization sysOrganization : sysOrganizationList) {
            SysOrganizationDTO sysOrganizationDTO = new SysOrganizationDTO();
            BeanUtils.copyProperties(sysOrganization, sysOrganizationDTO);
            sysOrganizationArray.add(sysOrganizationDTO);
        }
        return sysOrganizationArray;
    }

    /**
     * 获取指定机构列表的上级机构
     *
     * @param dtos
     * @return
     */
    public List<SysOrganizationDTO> getSuperOrganizations(List<SysOrganizationDTO> dtos) {

        List<SysOrganizationDTO> superOrganizations = new ArrayList<>();
        if (dtos.size() <= 0) return superOrganizations;

        List<String> ids = new ArrayList<>();
        for (SysOrganizationDTO dto : dtos) {
            String[] superIds = dto.getAllId().split(",");
            List<String> idList = new ArrayList<>(Arrays.asList(superIds));
            if (idList.size() > 1) {
                idList.remove(1);
            }
            ids.addAll(idList);
        }

        // 校验编码
        QueryWrapper<SysOrganization> qw = new QueryWrapper<>();
        qw.lambda().in(SysOrganization::getId, ids);
        List<SysOrganization> sysOrganizationList = this.baseMapper.selectList(qw);
        superOrganizations = sysOrganizationList.stream().map(p -> {
            SysOrganizationDTO sysOrganizationDTO = new SysOrganizationDTO();
            BeanUtils.copyProperties(p, sysOrganizationDTO);
            return sysOrganizationDTO;
        }).collect(Collectors.toList());

        return superOrganizations;
    }

    /**
     * 根据 主键 获取单条数据
     *
     * @param id 主键
     * @return SysOrganizationDTO
     */
    public SysOrganizationDTO get(String id) {
        // 查询数据
        SysOrganization item = this.baseMapper.selectById(id);
        SysOrganizationDTO sysOrganizationDTO = new SysOrganizationDTO();
        BeanUtils.copyProperties(item, sysOrganizationDTO);
        return sysOrganizationDTO;
    }

    /**
     * 校验合法性
     *
     * @param dto
     * @return
     */
    public RetResult<String> isValid(SysOrganizationDTO dto) {
        Integer count = 0;

        // 校验编码
        QueryWrapper<SysOrganization> qw = new QueryWrapper<>();

        if (!StrUtil.isEmpty(dto.getId())) {
            qw.lambda().ne(SysOrganization::getId, dto.getId());
        }
        if (!StrUtil.isEmpty(dto.getParentId())) {
            qw.lambda().eq(SysOrganization::getParentId, dto.getParentId());
        }
        qw.lambda().eq(SysOrganization::getOrganizationCode, dto.getOrganizationCode());
        qw.lambda().eq(SysOrganization::getDeleted, DeleteFlag.NOTDELETED.getValue());
        count = this.baseMapper.selectCount(qw);
        if (count > 0) {
            return RetResult.fail("当前父分类下机构编码已存在");
        }

        // 校验名称
        qw = new QueryWrapper<>();

        if (!StrUtil.isEmpty(dto.getId())) {
            qw.lambda().ne(SysOrganization::getId, dto.getId());
        }
        if (!StrUtil.isEmpty(dto.getParentId())) {
            qw.lambda().eq(SysOrganization::getParentId, dto.getParentId());
        }
        qw.lambda().eq(SysOrganization::getOrganizationName, dto.getOrganizationName());
        qw.lambda().eq(SysOrganization::getDeleted, DeleteFlag.NOTDELETED.getValue());
        count = this.baseMapper.selectCount(qw);
        if (count > 0) {
            return RetResult.fail("当前父分类下机构名称已存在");
        }
        return RetResult.ok();
    }

    /**
     * 插入对象
     *
     * @param dto 插入对象
     * @return SysOrganization
     */
    @Transactional(rollbackFor = Exception.class)
    public SysOrganizationDTO insert(SysOrganizationDTO dto) {

        SysOrganization item = new SysOrganization();
        BeanUtils.copyProperties(dto, item);

        // 默认数据
        item.setVersion(1L);
        this.setDefaultValue(item);
        item.setId(IdUtils.simpleUUID());
        item.setParentId(!StringUtils.isEmpty(dto.getParentId()) ? dto.getParentId() : "0");
        // 设置设置全主键、全编码、全名称
        this.setAllInfo(item);

        // 保存
        super.save(item);

        BeanUtils.copyProperties(item, dto);

        return dto;
    }

    /**
     * 更新对象
     *
     * @param dto 更新对象
     * @return CustomMultilevelKind
     */
    @Transactional(rollbackFor = Exception.class)
    public SysOrganizationDTO update(SysOrganizationDTO dto) {
        SysOrganization item = new SysOrganization();
        BeanUtils.copyProperties(dto, item);
        item.setParentId(!StringUtils.isEmpty(dto.getParentId()) ? dto.getParentId() : "0");
        // 默认数据
        this.setDefaultValue(item);
        // 设置设置全主键、全编码、全名称
        this.setAllInfo(item);
        // 保存
        super.updateById(item);

        return dto;
    }

    /**
     * 根据条件获取组织机构信息树
     *
     * @param query 查询条件
     * @return List<CustomMultilevelKindDTO>
     */
    public List<SysOrganizationDTO> getTree(SysOrganizationQuery query) {
        List<SysOrganizationDTO> tree = new ArrayList<>();
        // 获取所有组织机构
        List<SysOrganizationDTO> allList = this.getList(query);

        List<String> userIds = new ArrayList<>();
        for (SysOrganizationDTO sysOrganizationDTO : allList) {
            if (sysOrganizationDTO.getChargeManagerId() != null) userIds.add(sysOrganizationDTO.getChargeManagerId());
        }

        Map<String, String> map = new HashMap<>();
        if (userIds.size() > 0) {
            List<SysUser> users = sysUserService.listByIds(userIds);
            for (SysUser user : users) {
                map.put(user.getId(), user.getFirstName());
            }
        }

        // 获取上级机构
        List<SysOrganizationDTO> superList = this.getSuperOrganizations(allList);
        for (SysOrganizationDTO dto : superList) {
            Optional<SysOrganizationDTO> result = allList.stream().filter(p -> p.getId().equals(dto.getId())).findFirst();
            if (result.isPresent() == false) {
                allList.add(dto);
            }
        }

        Map<String, List<SysOrganizationDTO>> parentChildMap = new HashMap<>();
        // 将节点按照父节点进行分组
        for (SysOrganizationDTO node : allList) {
            node.setChargeManagerName(map.get(node.getChargeManagerId()));
            String parentId = node.getParentId();
            parentChildMap.computeIfAbsent(parentId, k -> new ArrayList<>()).add(node);
        }

        // 递归组装树结构
        buildTree(tree, parentChildMap, "0");

        return tree;
    }

    private void addChildNodes(List<SysOrganizationDTO> allList, SysOrganizationDTO node) {
        List<SysOrganizationDTO> childNodes = allList.stream().filter(p -> node.getId().equals(p.getParentId())).collect(Collectors.toList());
        node.setNodes(new ArrayList<>());
        for (SysOrganizationDTO childNode : childNodes) {
            node.getNodes().add(childNode);
            // 创建子节点
            this.addChildNodes(allList, childNode);
        }
    }

    /**
     * 根据条件获取用户分页列表
     *
     * @param tree           树
     * @param parentChildMap 节点集合
     * @param parentId       父id
     */
    private static void buildTree(List<SysOrganizationDTO> tree, Map<String, List<SysOrganizationDTO>> parentChildMap, String parentId) {
        List<SysOrganizationDTO> children = parentChildMap.get(parentId);
        if (children != null) {
            for (SysOrganizationDTO child : children) {
                List<SysOrganizationDTO> grandchildren = parentChildMap.get(child.getId());
                if (grandchildren != null) {
                    buildTree(child.getNodes(), parentChildMap, child.getId());
                }
                tree.add(child);
            }
        }
    }

    /**
     * 设置添加默认值
     *
     * @param item 添加对象
     */
    public void setDefaultValue(SysOrganization item) {
        if (StrUtil.isEmpty(item.getCreatedUserId())) {
            item.setCreatedUserId(SecurityUtils.getUserId());
            item.setCreateTime(new Date());
        }
        item.setLastUpdatedUserId(SecurityUtils.getUserId());
        item.setLastUpdateTime(new Date());

    }

    /**
     * 设置全主键、全编码、全名称
     */
    public void setAllInfo(SysOrganization item) {
        QueryWrapper<SysOrganization> qw = new QueryWrapper<>();
        qw.lambda().eq(SysOrganization::getId, item.getParentId());

        SysOrganization superCustomMultilevelKind = this.baseMapper.selectOne(qw);
        if (superCustomMultilevelKind == null) {
            item.setAllId(item.getId());
            item.setAllCode(item.getOrganizationCode());
            item.setAllName(item.getOrganizationName());
        } else {
            item.setAllId(superCustomMultilevelKind.getAllId() + "," + item.getId());
            item.setAllCode(superCustomMultilevelKind.getAllCode() + "," + item.getOrganizationCode());
            item.setAllName(superCustomMultilevelKind.getAllName() + "," + item.getOrganizationName());
        }
    }

    /**
     * 判断是否有下级机构
     *
     * @param id
     * @return
     */
    public Boolean isHaveChild(String id) {
        QueryWrapper<SysOrganization> qw = new QueryWrapper<>();
        qw.lambda().eq(SysOrganization::getParentId, id).eq(SysOrganization::getDeleted, 0);
        Integer count = this.baseMapper.selectCount(qw);
        return count > 0 ? true : false;
    }

    /**
     * 根据主键删除(逻辑删除)
     *
     * @param ids
     * @return bool
     */
    @Transactional(rollbackFor = Exception.class)
    public void logicDeleteList(List<String> ids) {
        // 删除
        UpdateWrapper<SysOrganization> uw = new UpdateWrapper<>();
        uw.lambda().in(SysOrganization::getId, ids);
        uw.set("deleted", DeleteFlag.DELETED.getValue());
        this.update(uw);

        QueryWrapper<RefUserOrganizationMapping> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().in(RefUserOrganizationMapping::getOrganizationId, ids);
        refUserOrganizationMappingService.remove(queryWrapper);

    }

    /**
     * 根据主键删除(物理删除)
     *
     * @param ids
     * @return bool
     */
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteByIds(String[] ids) {
        Boolean result = true;
        super.removeByIds(Arrays.asList(ids));
        return result;
    }

    /**
     * 获取公司主键
     *
     * @param id
     * @return
     */
    public String getCompanyId(String id) {
        String companyId = id;
        SysOrganizationDTO organizationDTO = this.getItemCache(id);
        if (organizationDTO.getOrganizationType() <= 2) {
            return id;
        }
        List<String> ids = Arrays.stream(organizationDTO.getAllId().split(",")).collect(Collectors.toList());

        for (int i = ids.size() - 2; i > 0; i--) {
            SysOrganizationDTO organization = this.getItemCache(ids.get(i));
            if (organization.getOrganizationType() <= 2) {
                return organization.getId();
            }
        }

        return companyId;
    }

    /**
     * 初始化缓存加载
     *
     * @return bool
     */
    @PostConstruct
    public Boolean intoCacheLoad() {
        // 删除缓存
        redisHashService.delete(redisKeyName);

        // 获取数据
        List<SysOrganizationDTO> list = this.getList(new SysOrganizationQuery());
        Map<String, SysOrganizationDTO> maps = list.stream().collect(Collectors.toMap(k -> k.getId().toLowerCase(), f -> f));

        // 写入到缓存
        redisHashService.setMap(redisKeyName, maps);
        return true;
    }

    /**
     * 刷新缓存
     *
     * @return bool
     */
    public Boolean refreshItemCache(SysOrganizationDTO dto) {
        // 定义缓存KEY
        String key = dto.getId();

        // 写入到缓存
        redisHashService.setMapValue(redisKeyName, key, dto);

        return true;
    }

    /**
     * 删除缓存
     *
     * @return bool
     */
    public Boolean deleteItemCache(String id) {
        // 定义缓存KEY
        String key = id;

        // 删除缓存
        redisHashService.removeMapValue(redisKeyName, key);

        return true;
    }

    /**
     * 删除缓存
     *
     * @return bool
     */
    public Boolean deleteItemCache(List<String> ids) {
        // 删除缓存
        redisHashService.removeMapValue(redisKeyName, ids);
        return true;
    }

    /**
     * 获取所有数据(缓存)
     *
     * @return List<SysOrganizationDTO>
     */
    public List<SysOrganizationDTO> getCacheList() {
        List<SysOrganizationDTO> list = new ArrayList<>();

        // 从缓存中获取
        Map<String, SysOrganizationDTO> maps = redisHashService.getMap(redisKeyName);

        // 从数据库中获取
        if (maps == null) {
            list = this.getList(new SysOrganizationQuery());
            return list;
        }

        list.addAll(maps.values());

        return list;
    }

    /**
     * 获取指定主键的数据(缓存)
     *
     * @return List<SysOrganizationDTO>
     */
    public List<SysOrganizationDTO> getCacheListByKeys(List<String> keys) {
        List<SysOrganizationDTO> list = new ArrayList<>();

        // 从缓存中获取
        List<Object> hKeys = Arrays.stream(keys.toArray()).collect(Collectors.toList());
        list = redisHashService.getMultiCacheMapValue(redisKeyName, hKeys);

        return list;
    }

    /**
     * 获取指定主键的数据(缓存)
     *
     * @return SysOrganizationDTO
     */
    public SysOrganizationDTO getItemCache(String id) {
        // 从缓存中获取
        SysOrganizationDTO item = redisHashService.getMapValue(redisKeyName, id);

        // 从数据库获取
        if (item == null) {
            item = this.get(id);
        }
        return item;
    }
}
